import json
import os
from urllib.request import urlretrieve

# 下载bookDetail资源
types = [{"value": "1", "desc": "课本"}, {"value": "3", "desc": "课外读物"}]
useListFileName = "use_bookList_{}.json"
# bookDetail_{publishingId}_{bookId}.json
bookFileName = "{}/bookDetail_{}_{}.json"
bookResourcePath = "resource/bookDetail_{}_{}/"
useBookFilePath = "use_{}/";
useBookFileName = "bookDetail_{}_{}.json";


def getFileName(url):
    resourcePaths = url.split('/')
    return resourcePaths[len(resourcePaths) - 1]


for ind, type in enumerate(types):
    listNameFile = open(useListFileName.format(type['value']), mode='r')
    list = json.loads(listNameFile.read())
    listNameFile.close()
    for ind, book in enumerate(list['data']):
        if (book['is_download'] == 0):
            bookDetail = json.loads(
                open(bookFileName.format(type['value'], book['publishing_id'], book['id']), mode='r').read())
            useBookPath = bookResourcePath.format(book['publishing_id'], book['id'])
            if not os.path.exists(useBookPath):
                os.makedirs(useBookPath)
            for ind, lesson in enumerate(bookDetail['data']['lessons']):
                audioUrl = lesson['audioUrl']
                imageUrl = lesson['imageUrl']
                if audioUrl is not None and imageUrl is not None:
                    audioName = getFileName(audioUrl)
                    imageName = getFileName(imageUrl)
                    try:
                        urlretrieve(audioUrl, useBookPath + audioName)
                    except BaseException:
                        print("下载音频失败：" + audioUrl + ";lessonId:" + lesson['lessonId'])
                    try:
                        urlretrieve(imageUrl, useBookPath + imageName)
                    except BaseException:
                        print("下载图片失败：" + imageUrl + ";lessonId:" + lesson['lessonId'])
                    lesson['local_audioUrl'] = useBookPath + audioName;
                    lesson['local_imageUrl'] = useBookPath + imageName;
                else:
                    print("解析name，失败音频或图片为空:" + json.dumps(lesson, ensure_ascii=False))
            for ind, page in enumerate(bookDetail['data']['pages']):
                imageUrl = page['imageUrl']
                imageName = getFileName(imageUrl)
                try:
                    urlretrieve(imageUrl, useBookPath + imageName)
                except BaseException:
                    print("下载每页图片失败：" + imageUrl)
                page['local_imageUrl'] = useBookPath + imageName
                for ind, lesson in enumerate(bookDetail['data']['lessons']):
                    if lesson["lessonId"] == page["lessonId"]:
                        for ind, sentence in enumerate(page['sentences']):
                            if "local_audioUrl" in lesson:
                                sentence['local_audioUrl'] = lesson['local_audioUrl']
            if not os.path.exists(useBookFilePath.format(book['book_type_id'])):
                os.makedirs(useBookFilePath.format(book['book_type_id']))
            useBookFile = open(
                useBookFilePath.format(book['book_type_id']) + useBookFileName.format(book['publishing_id'],
                                                                                      book['id']), mode="w")
            print(json.dumps(bookDetail, ensure_ascii=False), file=useBookFile)
            print("bookId:" + book['id'] +", 已经下载成功")
            useBookFile.close()
## 明天需要处理下载过的图书改到user_list的状态中，想一想有什么好的方式，让下载进度随时保存，而不是一起保存，如果一起保存项目一出异常数据就乱了
